package com.didispace;

import wn.tcpip.socket.util.Byte2Hex;
import wn.tcpip.socket.netty.decoder.Bytes2HexMessageDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * Created by zhangqin on 2017/4/19.
 */
public class Client {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        try {
            b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
            b.handler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ByteBuf delimiter = Unpooled.copiedBuffer(Byte2Hex.HexString2Bytes("0D0A"));//协议结尾
                    ch.pipeline().addLast( new DelimiterBasedFrameDecoder(1024, false,delimiter));//DelimiterBasedFrameDecoder会根据分隔符自动作为码流结束符来解决粘包问题
                    ch.pipeline().addLast(new Bytes2HexMessageDecoder());
                    ch.pipeline().addLast( new StringDecoder());
                    ch.pipeline().addLast(new GpsClientHandler());
                }
            });
            ChannelFuture f = b.connect("127.0.0.1", 10088);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            group.shutdownGracefully();
        }
    }

}
